﻿using Customer.Domain;
using Customer.Infrstructre.VendorManager;
using Customer.Read.API.Applcation.Command.VendorCommand;
using MediatR;

namespace Customer.Read.API.Applcation.CommandHandler.VendorCommandHandlers
{
    /// <summary>
    /// 显示供应商
    /// </summary>
    public class SelectVendorCommandHandler : IRequestHandler<SelectVendorCommand, Vendorpage>
    {
        private readonly IVendorRepository _vendorRep;
        public SelectVendorCommandHandler(IVendorRepository _vendorRep)
        {
            this._vendorRep = _vendorRep;
        }

        public async Task<Vendorpage> Handle(SelectVendorCommand request, CancellationToken cancellationToken)
        {
            Vendorpage page = new Vendorpage();
            var list = (await _vendorRep.GetAllAsync()).Where(t => t.Office_Id == request.Office_Id && t.IsDel == false);
            //供应商编号查询
            if (!string.IsNullOrEmpty(request.VendorCode))
            {
                list = list.Where(t => t.VendorCode == request.VendorCode);
            }
            //供应商名称模糊查询
            if (!string.IsNullOrEmpty(request.VendorName))
            {
                list = list.Where(t => t.VendorName.Contains(request.VendorName)).ToList();
            }
            //类型查询
            if (!string.IsNullOrEmpty(request.VendorType))
            {
                list = list.Where(t => t.VendorType == request.VendorType);
            }
            //电话查询
            if (!string.IsNullOrEmpty(request.Vphone))
            {
                list = list.Where(t => t.Vphone == request.Vphone);
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize == null)
            {
                request.PageSize = list.Count();
            }
            page.listcount = list.Count();
            page.pagecount = (int)Math.Ceiling(page.listcount * 1.0 / (int)request.PageSize);
            page.list = list.OrderByDescending(t=>t.VendorId).Skip(((int)request.PageIndex - 1) * (int)request.PageSize).Take((int)request.PageSize).ToList();
            return page;
        }
    }
}
